<?php

class User_Model_DbTable_User extends Custom_Db_Table_Abstract
{

    public	$_name	  = 'vt_users';

	protected $_referenceMap  = array(
									'Role' => array(
									   'columns'           => 'role_id',
									   'refTableClass'     => 'User_Model_DbTable_Role',
									   'refColumns'        => 'id'
									));

	public function sortedFields()
	{
		$fields = array(
					'id'=>'user.id',
					'fname'=>'user.first_name',
					'lname'=>'user.last_name',
					'email'=>'user.email',
					'role'=>'role.name'
		);

		return $fields;
	}

	public function processLogin($values, $config)
    {
        // Get our authentication adapter and check credentials
        $adapter = $this->getAuthAdapter();
        $adapter->setIdentity($values['email']);
        $adapter->setCredential(Custom_General::encrypt($values['password']));
       
        $auth   = Zend_Auth::getInstance();
        $result = $auth->authenticate($adapter);
        
        if ($result->isValid())
		{
            $user = $adapter->getResultRowObject();
			$objRole = new User_Model_DbTable_Role();
			
           	#fetch role
			$role = $objRole->getOne($user->role_id);
			
			$user->role = $role['name'];
			$auth->getStorage()->write($user);

			// Remember session
			if($values['rememberMe'])
			{
				Zend_Session::rememberMe(60*60*24*7);
			}
			else
			{
				Zend_Session::forgetMe();
			}   

			#user logged in log
			$this->_logger->info('User '. $user->first_name .' '. $user->last_name. ' Logged in');

            return true;
        }

        return false;
    }

    private function getAuthAdapter()
    {
        $dbAdapter      = self::getDefaultAdapter();
        $authAdapter    = new Zend_Auth_Adapter_DbTable($dbAdapter);

        $authAdapter->setTableName($this->_name)
            ->setIdentityColumn('email')
            ->setCredentialColumn('password');
         
        return $authAdapter;
    }

	public function get($ids)
	{
		if($ids)
		{
			if($this->_roleId == User_Model_DbTable_Role::ADMIN_USER)
				return $this->find(explode(',',$ids))->toArray();
			else 
				return $this->find($this->_userId)->toArray();
		}
		else
		{
			return false;
		}

	}

	public function getAll()
	{
		if($this->_roleId == User_Model_DbTable_Role::ADMIN_USER)
			return parent::fetchAll();
		else
			return $this->find($this->_userId)->toArray();
	}

	/**
	 * Use only for signup form
	 * @param <type> $data
	 * @return <type>
	 */
	public function save($data)
	{
		$form = new User_Form_SignUp();
		$form->setTranslator();
		
		if($form->isValid($data))
		{
			$saved_data = $form->getValues();
			$saved_data['password']	= Custom_General::encrypt($data['password']);
			$saved_data['role_id']	= User_Model_DbTable_Role::REGISTER_USER;
			
			return $this->insert($saved_data);
		}
		else
		{
			$err = array_values(array_filter($form->getErrors()));
			$this->setError($err);
			return false;
		}
	}

	/**
	 * Fetch user details with its role
	 * @return <type>
	 */
	public function fetchUsersWithRole($searchKey = '')
	{
		#if search key
		if($searchKey)
		{
			$where = '';
			foreach($this->sortedFields() as $field) $where .= $field." like '".$searchKey."%' OR ";
			$where = substr_replace($where, '', -3);
		}
		else
		{
			$where = '1=1';
		}
		
		$role	 = new User_Model_DbTable_Role();
		$select = $this->select()
					   ->setIntegrityCheck(false)
					   ->from(array('user' => $this->_name), array('user.*'))
					   ->join(array('role' => $role->_name), 'user.role_id = role.id', array('role.name as role_name'))
					   ->where($where)
					   ->order($this->getOrderBy());
		return $this->_applyPaginator($select)->toArray();
	}

}